#pragma once
#include "component.h"
#include <functional>
#include <memory>

#define RECV_BUFFER_SIZE 1024

class Connection {
  public:
    enum State {
        Invalid = 0,
        Connecting,
        Connected,
        Closed,
    };
    DISALLOW_COPY_AND_MOVE(Connection);
    Connection(int fd, EventLoop *loop);
    ~Connection();

    void set_delete_connection(std::function<void(int)> const &fn);
    void set_on_connect(std::function<void(Connection *)> const &fn);
    void set_on_recv(std::function<void(Connection *)> const &fn);
    State state() const;
    Socket *socket() const;
    char *read_buf();
    const char *send_buf();
    int get_recv_len();

    RC Read();
    int send(const uint8_t *str, int len);
    void Close();

    void onConnect(std::function<void()> fn);
    void onMessage(std::function<void()> fn);

  private:
    void Business();

  private:
    std::unique_ptr<Socket> socket_;
    std::unique_ptr<Channel> channel_;

    State state_;

    char read_buf_[RECV_BUFFER_SIZE];
    const char *send_buf_;
    int rx_len;
    int tx_len;

    std::function<void(int)> delete_connectioin_;
    std::function<void(Connection *)> on_recv_;
};
